package mqtt.simple.demo2;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Random;
import java.util.UUID;

public class TestMqttConnectBroker {
    /**
     * 代理服务器ip地址
     */
    public static final String MQTT_BROKER_HOST = "tcp://127.0.0.1:1889";
    /**
     * 客户端唯一标识
     */
    public static final String MQTT_CLIENT_ID = "1678415541515";
    /**
     * 订阅标识
     */
    public static final String MQTT_TOPIC = "test2";
    private static String USERNAME = "1740319256418201601";
    private static String PASSWORD = "CD881BDA6BC2F9D0FA2398380ADC1DF";

    private static MqttConnectOptions options;

    public static void main(String... args) throws MqttException {
        TestMqttConnectBroker broker = new TestMqttConnectBroker();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    broker.connect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        }
    }

    private void connect() throws MqttException {
        // host为主机名，clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，
        // MemoryPersistence设置clientid的保存形式，默认为以内存保存

        MqttClient mqttClient = new MqttClient(MQTT_BROKER_HOST, UUID.randomUUID().toString(), new MemoryPersistence());
        // 配置参数信息
        options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        // 这里设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        // 设置用户名
        options.setUserName(USERNAME);
        // 设置密码
        options.setPassword(PASSWORD.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(1);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(30);
        // 连接
        long begin = System.currentTimeMillis();
        mqttClient.connect(options);

        System.out.println(System.currentTimeMillis() - begin);

        // 订阅
//            mqttClient.subscribe(MQTT_TOPIC);
        // 设置回调
//        mqttClient.setCallback(new MqttCallback() {
//            @Override
//            public void connectionLost(Throwable throwable) {
//                System.out.println("connectionLost");
//            }
//
//            @Override
//            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
//                System.out.println("Topic: " + s + " Message: " + mqttMessage.toString());
//            }
//
//            @Override
//            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//                System.out.println("iMqttDeliveryToken: " + iMqttDeliveryToken.toString());
//
//            }
//        });
        mqttClient.disconnect();
    }

}
